<template>
  <TableLayout :permissions="['system:permission:query']">
    <!-- 表格和分页 -->
    <template v-slot:table-wrap>
      <el-tabs>
        <el-tab-pane :label="module.name" v-for="module in tableData.list" :key="module.name">
          <ul class="toolbar" v-permissions="['system:permission:create', 'system:permission:delete']">
            <li><el-button type="primary" @click="$refs.operaPermissionWindow.open('新建系统权限')" icon="el-icon-plus" v-permissions="['system:permission:create']">新建</el-button></li>
            <li><el-button @click="$refs.operaPermissionWindow.open('新建系统权限')" v-permissions="['system:permission:create']">设置模块</el-button></li>
            <li><el-button @click="deleteByIdInBatch" icon="el-icon-delete" v-permissions="['system:permission:delete']">删除</el-button></li>
          </ul>
          <el-table
            v-loading="isWorking.search"
            :data="module.children"
            :default-sort = "{prop: 'createTime', order: 'descending'}"
            row-key="id"
            stripe
            :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
            default-expand-all
            @selection-change="handleSelectionChange"
            @sort-change="handleSortChange"
          >
            <el-table-column type="selection" fixed="left" width="55"></el-table-column>
            <el-table-column prop="name" label="权限名称" fixed="left" min-width="200px"></el-table-column>
            <el-table-column prop="code" label="权限编码" min-width="200px"></el-table-column>
            <el-table-column prop="remark" label="权限备注" min-width="120px"></el-table-column>
            <el-table-column prop="createUser" label="创建人" min-width="100px">
              <template slot-scope="{row}">{{row.createUserInfo == null ? '' : row.createUserInfo.username}}</template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" min-width="140px" sortable="custom" sort-by="perm.CREATE_TIME"></el-table-column>
            <el-table-column prop="updateUser" label="更新人" min-width="100px">
              <template slot-scope="{row}">{{row.updateUserInfo == null ? '' : row.updateUserInfo.username}}</template>
            </el-table-column>
            <el-table-column prop="updateTime" label="更新时间" min-width="140px"></el-table-column>
            <el-table-column
              v-if="containPermissions(['system:permission:update', 'system:permission:delete'])"
              label="操作"
              min-width="130"
              fixed="right"
            >
              <template slot-scope="{row}">
                <el-button v-if="!row.fixed" type="text" @click="$refs.operaPermissionWindow.open('编辑系统权限', row)" icon="el-icon-edit" v-permissions="['system:permission:update']">编辑</el-button>
                <el-button v-if="!row.fixed" type="text" @click="deleteById(row)" icon="el-icon-delete" v-permissions="['system:permission:delete']">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </template>
    <!-- 新建/修改 -->
    <OperaPermissionWindow ref="operaPermissionWindow" @success="search"/>
  </TableLayout>
</template>

<script>
import TableLayout from '@/layouts/TableLayout'
import BaseTable from '@/components/base/BaseTable'
import OperaPermissionWindow from '@/components/system/permission/OperaPermissionWindow'
export default {
  name: 'SystemPermission',
  extends: BaseTable,
  components: { OperaPermissionWindow, TableLayout },
  methods: {
    search () {
      this.isWorking.search = true
      this.api.fetchAll()
        .then(data => {
          const nodes = []
          for (const record of data) {
            if (record.module == null || record.module == '') {
              record.module = '其它'
            }
            const paths = record.module.split('/')
            let modules = []
            let parentNode = null
            let targetNode = null
            for (const path of paths) {
              modules.push(path)
              targetNode = this.__getModuleNode(nodes, modules.join('/'))
              if (targetNode == null) {
                targetNode = {
                  id: 'module_' + Math.round(Math.random() * 10000),
                  type: 'module',
                  name: path,
                  children: []
                }
                if (parentNode != null) {
                  parentNode.children.push(targetNode)
                } else {
                  nodes.push(targetNode)
                }
              }
              parentNode = targetNode
            }
            targetNode.children.push(record)
          }
          this.tableData.list = nodes
        })
        .catch(e => {
          this.$tip.apiFailed(e)
          throw new Error(e)
        })
        .finally(() => {
          this.isWorking.search = false
        })
    },
    // 查询权限模块
    __getModuleNode(nodes, module) {
      const paths = module.split('/')
      let list = nodes
      const nodeStack = []
      for (const path of paths) {
        if (list == null) {
          break
        }
        for (const node of list) {
          if (node.name === path && node.type === 'module') {
            nodeStack.push(node)
            list = node.children
            break
          }
        }
      }
      return nodeStack.length === paths.length ? nodeStack[nodeStack.length - 1] : null
    },
    //
    __afterDelete () {
      this.search()
    }
  },
  created () {
    this.config({
      module: '权限',
      api: '/system/permission',
      sorts: [{
        property: 'perm.CREATE_TIME',
        direction: 'DESC'
      }]
    })
    this.search()
  }
}
</script>

<style scoped lang="scss">
  /deep/ .table-content .table-wrap {
    padding-bottom: 16px;
  }
</style>
